#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
from src.core.document_processor import DocumentProcessor
from src.core.text_cleaner import TextCleaner

def debug_paragraph_structure():
    """调试段落结构信息"""
    
    # 文档路径
    doc_path = r"e:\trae\dify\data\面向水库风险监测的低成本低功耗边缘智能系统.docx"
    
    # 创建文档处理器
    cleaning_config = {
        'remove_headers_footers': True,
        'remove_special_chars': True,
        'remove_duplicates': True,
        'fix_line_breaks': True,
        'remove_empty_lines': True
    }
    
    chunking_config = {
        'strategy': 'structural',
        'max_chunk_size': 1000,
        'overlap_size': 100,
        'include_headers': True
    }
    
    processor = DocumentProcessor(cleaning_config, chunking_config)
    
    # 处理文档
    print("正在处理文档...")
    result = processor.process_file(doc_path)
    
    if not result:
        print("文档处理失败")
        return
    
    # 从raw_content中获取文本和结构
    raw_content = result.get('raw_content', {})
    text = raw_content.get('text', '')
    structure = raw_content.get('structure', {})
    
    print(f"文本长度: {len(text)}")
    print(f"结构键: {list(structure.keys())}")
    
    # 检查段落结构
    paragraphs = structure.get('paragraphs', [])
    print(f"\n段落数量: {len(paragraphs)}")
    
    # 显示前10个段落的详细信息
    print("\n前10个段落的详细信息:")
    for i, para in enumerate(paragraphs[:10]):
        print(f"段落 {i}:")
        print(f"  键: {list(para.keys())}")
        if 'text' in para:
            print(f"  文本: {para['text'][:100]}...")
        if 'start_pos' in para:
            print(f"  开始位置: {para['start_pos']}")
        if 'end_pos' in para:
            print(f"  结束位置: {para['end_pos']}")
        print()
    
    # 检查标题对应的段落
    headings = structure.get('headings', [])
    print(f"\n标题数量: {len(headings)}")
    
    print("\n标题对应的段落信息:")
    for heading in headings[:5]:  # 只显示前5个标题
        para_index = heading.get('paragraph_index', -1)
        print(f"标题: {heading.get('text', '')[:50]}...")
        print(f"  段落索引: {para_index}")
        
        if para_index < len(paragraphs):
            para = paragraphs[para_index]
            print(f"  对应段落键: {list(para.keys())}")
            if 'text' in para:
                print(f"  段落文本: {para['text'][:100]}...")
            if 'start_pos' in para:
                print(f"  段落开始位置: {para['start_pos']}")
        else:
            print(f"  段落索引超出范围!")
        print()
    
    # 保存调试结果
    debug_result = {
        'text_length': len(text),
        'paragraph_count': len(paragraphs),
        'heading_count': len(headings),
        'sample_paragraphs': paragraphs[:5],  # 前5个段落的完整信息
        'sample_headings': headings[:5]  # 前5个标题的完整信息
    }
    
    with open('debug_paragraph_structure_result.json', 'w', encoding='utf-8') as f:
        json.dump(debug_result, f, ensure_ascii=False, indent=2)
    
    print("\n调试信息已保存到: debug_paragraph_structure_result.json")

if __name__ == "__main__":
    debug_paragraph_structure()